package org.xteam.box2text.oaw;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;

import org.eclipse.xtend.expression.Resource;
import org.xteam.box2text.parser.BoxLexer;
import org.xteam.box2text.parser.BoxParser;
import org.xteam.box2text.parser.ast.BoxFile;
import org.xteam.parser.runtime.DefaultErrorReporter;
import org.xteam.parser.runtime.IErrorReporter;
import org.xteam.parser.runtime.NullErrorReporter;

public class BoxParseFacade {

	public static Resource file(Reader in, String fileName) {
		String str = readFile(in);
		DefaultErrorReporter reporter = new DefaultErrorReporter(System.out);
		BoxParser parser = new BoxParser(new BoxLexer(new StringReader(str), reporter), reporter);
		BoxFile file = null;
		try {
			file = (BoxFile) parser.parse().value;
			return new BoxResourceImpl(file);
		} catch (Exception e) {
			try {
				reporter.printDiagnostic(new StringReader(str));
			} catch (IOException exp) {
			}
		}
		return new BadBoxResource();
	}
	
	private static String readFile(Reader in) {
		StringBuffer buffer = new StringBuffer();
		try {
			char[] buf = new char[512];
			while (in.ready()) {
				int len = in.read(buf);
				buffer.append(new String(buf, 0, len));
			}
		} catch (IOException e) {
		}
		return buffer.toString();
	}

	private static class BadBoxResource implements BoxResource {

		private String fqn;
		
		@Override
		public BoxRule[] getRules() {
			return new BoxRule[0];
		}

		@Override
		public String getFullyQualifiedName() {
			return fqn;
		}
		
		@Override
		public void setFullyQualifiedName(String fqn) {
			this.fqn = fqn;
		}

		@Override
		public String[] getImportedExtensions() {
			return new String[0];
		}

		@Override
		public String[] getImportedNamespaces() {
			return new String[0];
		}
		
	}
}
